package com.central.scheduler.service.log;

import com.central.scheduler.common.utils.LoggerUtils;
import com.central.scheduler.common.utils.NetUtils;
import com.central.scheduler.remote.NettyRemotingClient;
import com.central.scheduler.remote.command.Command;
import com.central.scheduler.remote.command.log.*;
import com.central.scheduler.remote.config.NettyClientConfig;
import com.central.scheduler.remote.utils.Host;
import com.central.scheduler.common.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Tindy
 * @date 2021/10/29
 * @describe
 */
public class LogClientService implements AutoCloseable {

    private static final Logger logger = LoggerFactory.getLogger(LogClientService.class);

    private final NettyClientConfig clientConfig;

    private final NettyRemotingClient client;

    private volatile boolean isRunning;

    /**
     * request time out
     */
    private static final long LOG_REQUEST_TIMEOUT = 10 * 1000L;

    /**
     * construct client
     */
    public LogClientService() {
        this.clientConfig = new NettyClientConfig();
        this.clientConfig.setWorkerThreads(4);
        this.client = new NettyRemotingClient(clientConfig);
        this.isRunning = true;
    }

    /**
     * close
     */
    @Override
    public void close() {
        this.client.close();
        this.isRunning = false;
        logger.info("logger client closed");
    }

    /**
     * roll view log
     *
     * @param host host
     * @param port port
     * @param path path
     * @param skipLineNum skip line number
     * @param limit limit
     * @return log content
     */
    public String rollViewLog(String host, int port, String path, int skipLineNum, int limit) {
        logger.info("roll view log, host : {}, port : {}, path {}, skipLineNum {} ,limit {}", host, port, path, skipLineNum, limit);
        RollViewLogRequestCommand request = new RollViewLogRequestCommand(path, skipLineNum, limit);
        String result = "";
        final Host address = new Host(host, port);
        try {
            Command command = request.convert2Command();
            Command response = this.client.sendSync(address, command, LOG_REQUEST_TIMEOUT);
            if (response != null) {
                RollViewLogResponseCommand rollReviewLog = JSONUtils.parseObject(
                        response.getBody(), RollViewLogResponseCommand.class);
                return rollReviewLog.getMsg();
            }
        } catch (Exception e) {
            logger.error("roll view log error", e);
        } finally {
            this.client.closeChannel(address);
        }
        return result;
    }

    /**
     * view log
     *
     * @param host host
     * @param port port
     * @param path path
     * @return log content
     */
    public String viewLog(String host, int port, String path) {
        logger.info("view log path {}", path);
        ViewLogRequestCommand request = new ViewLogRequestCommand(path);
        String result = "";
        final Host address = new Host(host, port);
        try {
            if (NetUtils.getHost().equals(host)) {
                result = LoggerUtils.readWholeFileContent(request.getPath());
            } else {
                Command command = request.convert2Command();
                Command response = this.client.sendSync(address, command, LOG_REQUEST_TIMEOUT);
                if (response != null) {
                    ViewLogResponseCommand viewLog = JSONUtils.parseObject(
                            response.getBody(), ViewLogResponseCommand.class);
                    result = viewLog.getMsg();
                }
            }
        } catch (Exception e) {
            logger.error("view log error", e);
        } finally {
            this.client.closeChannel(address);
        }
        return result;
    }

    /**
     * get log size
     *
     * @param host host
     * @param port port
     * @param path log path
     * @return log content bytes
     */
    public byte[] getLogBytes(String host, int port, String path) {
        logger.info("log path {}", path);
        GetLogBytesRequestCommand request = new GetLogBytesRequestCommand(path);
        byte[] result = null;
        final Host address = new Host(host, port);
        try {
            Command command = request.convert2Command();
            Command response = this.client.sendSync(address, command, LOG_REQUEST_TIMEOUT);
            if (response != null) {
                GetLogBytesResponseCommand getLog = JSONUtils.parseObject(
                        response.getBody(), GetLogBytesResponseCommand.class);
                return getLog.getData();
            }
        } catch (Exception e) {
            logger.error("get log size error", e);
        } finally {
            this.client.closeChannel(address);
        }
        return result;
    }

    /**
     * remove task log
     *
     * @param host host
     * @param port port
     * @param path path
     * @return remove task status
     */
    public Boolean removeTaskLog(String host, int port, String path) {
        logger.info("log path {}", path);
        RemoveTaskLogRequestCommand request = new RemoveTaskLogRequestCommand(path);
        Boolean result = false;
        final Host address = new Host(host, port);
        try {
            Command command = request.convert2Command();
            Command response = this.client.sendSync(address, command, LOG_REQUEST_TIMEOUT);
            if (response != null) {
                RemoveTaskLogResponseCommand taskLogResponse = JSONUtils.parseObject(
                        response.getBody(), RemoveTaskLogResponseCommand.class);
                return taskLogResponse.getStatus();
            }
        } catch (Exception e) {
            logger.error("remove task log error", e);
        } finally {
            this.client.closeChannel(address);
        }
        return result;
    }

    public boolean isRunning() {
        return isRunning;
    }

}
